package cn.denvie.agent.configsource;

import cn.denvie.agent.utils.StringUtils;
import org.stagemonitor.configuration.source.AbstractConfigurationSource;

import java.util.HashMap;
import java.util.Map;

/**
 * Agent代理参数配置源，如果“java -javaagent:/root/agent.jar=param”中设置的param参数。
 *
 * @author DengZhaoyong
 * @version 1.0.0
 */
public class AgentArgumentConfigurationSource extends AbstractConfigurationSource {

    private final Map<String, String> config;

    private AgentArgumentConfigurationSource(Map<String, String> config) {
        this.config = config;
    }

    public static AgentArgumentConfigurationSource parse(String agentArgument) {
        final Map<String, String> configs = new HashMap<>();
        for (String config : StringUtils.split(agentArgument, ';')) {
            final int indexOfEquals = config.indexOf('=');
            if (indexOfEquals < 1) {
                throw new IllegalArgumentException(String.format("%s is not a '=' separated key/value pair", config));
            }
            configs.put(config.substring(0, indexOfEquals).trim(), config.substring(indexOfEquals + 1).trim());
        }
        return new AgentArgumentConfigurationSource(configs);
    }

    @Override
    public String getValue(String key) {
        return config.get(key);
    }

    @Override
    public String getName() {
        return "-javaagent options";
    }

    Map<String, String> getConfig() {
        return config;
    }

}